﻿using System.IO;
using System.Net.Mail;

namespace AxeFrog.Net
{
	public class Emailer
	{
		public string Host { get; set; }
		public int? Port { get; set; }
		public string Username { get; set; }
		public string Password { get; set; }

		public string Template { get; set; }
		public string Subject { get; set; }

		public Emailer() { }
		public Emailer(string host, int port)
		{
			Host = host;
			Port = port;
		}
		public Emailer(string username, string password)
		{
			Username = username;
			Password = password;
		}
		public Emailer(string host, int port, string username, string password)
		{
			Host = host;
			Port = port;
			Username = username;
			Password = password;
		}

		public void Send(
			string fromName,
			string fromEmail,
			string recipientName,
			string recipientEmail,
			object values)
		{
			Send(Template, Subject,
			     fromName, fromEmail, recipientName, recipientEmail,
			     Host, Port, Username, Password, values);
		}

		public void Send(
			string templatePath,
			string subject,
			string fromName,
			string fromEmail,
			string recipientName,
			string recipientEmail,
			object values)
		{
			string str = File.ReadAllText(templatePath);
			Send(str, subject,
			     fromName, fromEmail, recipientName, recipientEmail,
			     Host, Port, Username, Password, values);
		}

		public void Send(
			string body,
			string subject,
			string fromName,
			string fromEmail,
			string recipientName,
			string recipientEmail)
		{
			Send(body, subject,
			     fromName, fromEmail, recipientName, recipientEmail,
			     Host, Port, Username, Password, new object());
		}

		public static void Send(
			string template,
			string subject,
			string fromName,
			string fromEmail,
			string recipientName,
			string recipientEmail,
			string host,
			int? port,
			string username,
			string password,
			object values)
		{
			var client = new SmtpClient();
			if (host != null)
				client.Host = host;
			if (port.HasValue)
				client.Port = port.Value;
			if (username != null && password != null)
				client.Credentials = new System.Net.NetworkCredential(username, password);

			MailMessage msg = new MailMessage(
				new MailAddress(fromEmail, fromName),
				new MailAddress(recipientEmail, recipientName)
				);
			msg.Subject = subject;
			msg.Body = template.ReplaceTokens("[", "]", values);
			//client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
			client.Send(msg);           
		}
	}
}